/**
 * @file reordering.cpp
 * @author your name (you@domain.com)
 * @brief 演示x86下store load重排序问题
 * @version 0.1
 * @date 2022-09-06
 * 
 * @copyright Copyright (c) 2022
 * 
 * @note reordering是CPU在执行期间的行为，与编译器无关。因此即使不开优化编译，也能出现reordering的现象
 * 
 */

#include <iostream>
#include <thread>

int gX, gY;
int gR1, gR2;

void fun1(void)
{
  gX = 1;
  gR1 = gY;
}

void fun2(void)
{
  gY = 1;
  gR2 = gX;
}

int main(void)
{
  for (int i = 0; ; i++)
  {
    gX = 0;
    gY = 0;

    std::thread t1(fun1);
    std::thread t2(fun2);

    t1.join();
    t2.join();

    if (gR1 == 0 && gR2 == 0)
    {
      std::cout<< "reordering happend in iteration " << i << std::endl;
    }
  }
}